<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="goodsSearch" class="demo-form-inline">
        <!-- 查询表单 -->
        <el-form-item>
          <el-input v-model="goodsSearch.productName" placeholder="货物名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="goodsSearch.description" placeholder="货物描述"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="goodsSearch.shelfId" placeholder="货架">
            <el-option label="所有货架" value="0"></el-option>
            <el-option :label="s.name" :value="s.sid" v-for="s in shelvesList" :key="s.sid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addGoods">添加货物</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <!-- 货物列表表格 -->
      <el-table
          :data="goodsList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="货物编号"
            align="center"
            prop="productId"
            width="180"/>
        <el-table-column
            label="货物名称"
            prop="productName"
            align="center"/>
        <el-table-column
            label="价格"
            prop="price"
            align="center"/>
        <el-table-column
            label="描述"
            prop="description"
            align="center"/>
        <el-table-column
            label="库存"
            prop="stock"
            align="center"/>
        <el-table-column
            label="货架"
            prop="shelfName"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页控件 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <!-- 编辑/新增货物对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      {{goods}}
      <el-form :model="goods" :rules="rules" ref="ruleForm">
        <el-form-item label="货物名称" prop="productName" :label-width="formLabelWidth">
          <el-input v-model="goods.productName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price" :label-width="formLabelWidth">
          <el-input v-model.number="goods.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description" :label-width="formLabelWidth">
          <el-input v-model="goods.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="stock" :label-width="formLabelWidth">
          <el-input v-model.number="goods.stock" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="货架" prop="shelfId" :label-width="formLabelWidth">
          <el-select v-model="goods.shelfId" placeholder="请选择货架">
            <el-option label="所有货架" value="0"></el-option>
            <el-option :label="s.name" :value="s.sid" v-for="s in shelvesList" :key="s.sid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveGoods">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import goodsApi from "@/api/GoodsService"
import shelfApi from "@/api/ShelfService"

export default {
  data() {
    // 自定义校验规则
    let checkPrice = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('价格不能为空'))
      } else if (value <= 0) {
        return callback(new Error('价格必须大于0'))
      } else {
        callback()
      }
    }

    return {
      goodsList: [], // 货物列表
      page: 1,        // 当前页
      pageSize: 5,    // 每页显示记录条数
      total: 100,     // 总记录数
      goodsSearch: {}, // 查询条件对象
      shelvesList: [],   // 货架列表
      dialogFormVisible: false,  // 控制对话框显示
      goods: {},       // 当前操作的货物对象
      title: '添加货物',  // 对话框标题
      formLabelWidth: '100px',  // 代表表单的标签宽度
      multipleSelection:[],     // 选中的多项货物
      goodsIds: [],                 // 删除的货物编号列表
      // 校验规则
      rules: {
        productName: [{ required: true, message: '请输入货物名称', trigger: 'blur' }],
        price: [{ validator: checkPrice, trigger: 'blur'}],
        description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
        shelfId: [{ required: true, message: '请选择货架', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.search()
    this.findAllShelves()
  },
  methods: {
    // 获取所有货架的信息
    async findAllShelves() {
      const {data: res} = await shelfApi.findAllShelves()
      if (res.code === 200) {
        this.shelvesList = res.data.list
      }
    },
    // 条件查询带分页，""可查出全部数据
    async search() {
      const {data: res} = await goodsApi.search(this.page, this.pageSize, this.goodsSearch)
      if (res.code === 200) {
        this.goodsList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    // 添加货物
    addGoods() {
      this.title = "添加货物"
      this.goods = {}
      this.dialogFormVisible = true
    },
    // 保存货物
    saveGoods() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const url = this.goods.productId ? '/goods/update' : '/goods/add';
          const method = this.goods.productId ? 'put' : 'post';
          const {data: res} = await goodsApi.save(url, method, this.goods)
          if (res.code === 200) {
            this.$message({ type: 'success', message: res.message });
            this.dialogFormVisible = false;
            this.search();
          } else {
            this.$message({ type: 'error', message: res.message });
          }

        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 当pageSize大小发生改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.search()
    },
    // 当页码page发生改变时触发
    handleCurrentChange(val) {
      this.page = val
      this.search()
    },
    // 修改货物
    handleEdit(index, row) {
      this.title = '修改货物'
      this.goods = row
      this.dialogFormVisible = true
    },
    handleDelete(index, row) {
      this.goodsIds = row ? [row.productId] : this.multipleSelection.map(m => m.productId);
      this.$confirm(`确认删除编号为${this.goodsIds}的货物吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        goodsApi.delete(this.goodsIds)
            .then(({data: res}) => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style>
#app {
  display: flex;
  justify-content: center;
}

.el-card {
  width: 90%;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
